package com.ca.project.Server.Modules.TweetsImg.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ca.project.COS.CosUtil;
import com.ca.project.Minio.Util.MinioUtil;
import com.ca.project.Server.Modules.TweetsImg.Context.ReturnPicContext;
import com.ca.project.Server.Modules.TweetsImg.Context.UploadImgContext;
import com.ca.project.Server.Modules.TweetsImg.Converter.TweetsImgConverter;
import com.ca.project.Server.Modules.TweetsImg.Entity.TweetsImg;
import com.ca.project.Server.Modules.TweetsImg.Service.TweetsImgService;
import com.ca.project.Server.Modules.TweetsImg.Mapper.TweetsImgMapper;
import com.ca.project.core.Exception.BusinessException;
import com.ca.project.core.Util.IdUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ASUS
 * @description 针对表【tweets_img】的数据库操作Service实现
 * @createDate 2024-12-31 15:10:09
 */
@Service
public class TweetsImgServiceImpl extends ServiceImpl<TweetsImgMapper, TweetsImg>
        implements TweetsImgService {

    @Autowired
    private CosUtil cosUtil;
    @Autowired
    private TweetsImgConverter tweetsImgConverter;
    @Autowired
    private MinioUtil minioUtil;

    /**
     * 删除上传的推文图片
     *
     * @param tTitle
     */
    @Override
    public void deleteImg(String tTitle) {
        List<TweetsImg> list = findByTitle(tTitle);
        doDelete(list);
    }

    /**
     * 图片上传
     *
     * @param uploadImgContext
     * @return
     */
    @Override
    public TweetsImg upload(UploadImgContext uploadImgContext) {
        doUpload(uploadImgContext);
        doCreate(uploadImgContext);
        return uploadImgContext.getEntity();
    }

    /**
     * 图片删除
     *
     * @param filename
     */
    @Override
    public void delete(String filename) {
        try {
            cosUtil.deletePublicFile(filename);
        } catch (Exception e) {
            throw new BusinessException("云端图片删除失败" + e.getMessage());
        }
        QueryWrapper<TweetsImg> wrapper = new QueryWrapper<>();
        wrapper.eq("p_img_key", filename);
        boolean success = baseMapper.delete(wrapper) > 0;
        if (!success)
            throw new BusinessException("商品图片删除失败");
    }

    /**
     * 分页
     *
     * @param currentPage
     * @param pageSize
     * @param tweetsImg
     * @return
     */
    @Override
    public IPage<TweetsImg> getPage(Integer currentPage, Integer pageSize, TweetsImg tweetsImg) {
        LambdaQueryWrapper<TweetsImg> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(tweetsImg.getTImgName())) {
            wrapper.like(TweetsImg::getTImgName, tweetsImg.getTImgName());
        }
        IPage<TweetsImg> page = new Page<>(currentPage, pageSize);
        baseMapper.selectPage(page, wrapper);
        return page;
    }

    /**
     * 分页
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public IPage<TweetsImg> getPage(Integer currentPage, Integer pageSize) {
        IPage<TweetsImg> page = new Page<>(currentPage, pageSize);
        baseMapper.selectPage(page, null);
        return page;
    }

    /**
     * 根据推文名称返回图片
     *
     * @param returnPicContext
     * @return
     */
    @Override
    public Object getPic(ReturnPicContext returnPicContext) {
        QueryWrapper<TweetsImg> wrapper = new QueryWrapper<>();
        wrapper.eq("t_title", returnPicContext.getT_title());
        return baseMapper.selectList(wrapper);
    }
/*************************************************************private*******************************************/

    /**
     * 查找该推文的所有照片
     *
     * @param tTitle
     * @return
     */
    private List<TweetsImg> findByTitle(String tTitle) {
        QueryWrapper<TweetsImg> wrapper = new QueryWrapper<>();
        wrapper.eq("t_title", tTitle);
        List<TweetsImg> entity = baseMapper.selectList(wrapper);
        if (entity.isEmpty())
            return Collections.emptyList();
        return entity;
    }

    /**
     * 删除操作
     *
     * @param list
     */
    private void doDelete(List<TweetsImg> list) {
        if (Objects.isNull(list) || list.isEmpty())
            return;
        List<String> keys = list.stream()
                .map(TweetsImg::getTImgKey)
                .collect(Collectors.toList());
        boolean deleteFile = minioUtil.deleteFile(keys.toString());
        if (!deleteFile)
            throw new BusinessException("minio云删除失败");
        List<Long> ids = list.stream()
                .map(TweetsImg::getTImgId)
                .collect(Collectors.toList());
        boolean success = baseMapper.deleteBatchIds(ids) > 0;
        if (!success)
            throw new BusinessException("推文图片删除失败");
    }

    /**
     * 图片上传
     *
     * @param uploadImgContext
     */
    private void doUpload(UploadImgContext uploadImgContext) {
        TweetsImg entity = tweetsImgConverter.UploadImgContext2ProductImg(uploadImgContext);

        MultipartFile file = uploadImgContext.getFile();
        if (file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }
        String filename = file.getOriginalFilename();
        if (filename.isEmpty())
            throw new BusinessException("上传文件名不能为空");
        if (filename.contains(".")) {
            filename = filename.substring(0, filename.lastIndexOf('.'));
        }
        try {
            //String path = "/CA/";
            //HashMap map = cosUtil.uploadPublicFile(file, path);
            Map<String, Object> map = minioUtil.upload(file);

            //String key = (String) map.get("path");
            String url = (String) map.get("url");
            String key = (String) map.get("key");

            //if (key.startsWith("/")) {
            //    key = key.substring(1);
            //}

            final Long id = IdUtil.get();
            entity.setTImgId(id);
            entity.setTUpdateUser(uploadImgContext.getT_update_user());
            entity.setTTitle(uploadImgContext.getT_title());
            entity.setTImgName(filename);
            entity.setTImgKey(key);
            entity.setUrl(url);
            entity.setCreateTime(new Date());

            uploadImgContext.setEntity(entity);
        } catch (IOException e) {
            throw new BusinessException("文件上传到腾讯云错误");
        }
    }

    /**
     * 创建实体
     *
     * @param uploadImgContext
     */
    private void doCreate(UploadImgContext uploadImgContext) {
        TweetsImg entity = uploadImgContext.getEntity();
        if (entity == null)
            throw new BusinessException("推文图片实体不能为空");

        try {
            if (!save(entity))
                throw new BusinessException("推文图片创建失败");
        } catch (Exception e) {
            throw new BusinessException("推文图片创建失败,原因:" + e.getMessage());
        }
    }
}




